package com.jy.horny

import android.content.Context
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import android.widget.Toast

/**
 * Created by kaiwang on 2017/11/17.
 */
object ToastUtil {
    fun showToast(resId: Int) {
        show(App.instance.resources.getString(resId), Toast.LENGTH_SHORT)
    }

    fun showToast(text: String?) {
        if (TextUtils.isEmpty(text)) return
        show(text!!, Toast.LENGTH_SHORT)
    }

    fun showLongToast(resId: Int) {
        show(App.instance.resources.getString(resId), Toast.LENGTH_LONG)
    }

    fun showLongToast(text: String) {
        show(text, Toast.LENGTH_LONG)
    }

    fun showToast(context: Context, resId: Int, isSystem: Boolean) {
        if (isSystem) systemShow(
            context,
            App.instance.resources.getString(resId),
            Toast.LENGTH_SHORT
        ) else show(App.instance.resources.getString(resId), Toast.LENGTH_SHORT)
    }

    private fun systemShow(context: Context, text: String, showTimeLong: Int) {
        Toast.makeText(context, text, showTimeLong)
    }

    /**
     * 自定义 toast
     * @param context
     * @param messages
     * @param showTimeLong
     */
    private fun show(messages: String, showTimeLong: Int) {
        var messages = messages
        try {
            if (TextUtils.isEmpty(messages)) {
                return
            }
            messages = messages.trim { it <= ' ' }
            val inflater: LayoutInflater = LayoutInflater.from(App.instance)
            val view: View = inflater.inflate(R.layout.view_toast, null)
            val messagesTv: TextView = view.findViewById<TextView>(R.id.view_toast_tv)
            messagesTv.gravity = Gravity.CENTER
            messagesTv.text = messages
            val toast = Toast(App.instance)
            toast.setGravity(Gravity.CENTER, 12, 20)
            toast.duration = showTimeLong
            toast.view = view
            toast.show()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}